<template>
  <div class="documents-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div>
          <h1 class="page-title">文档管理</h1>
          <p class="page-subtitle">管理和查看所有文档，支持多种格式预览</p>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="showUploadDialog = true">
            <el-icon><Upload /></el-icon>
            上传文档
          </el-button>
        </div>
      </div>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <!-- 视图切换 -->
        <el-radio-group v-model="viewMode" size="small">
          <el-radio-button value="grid">
            <el-icon><Grid /></el-icon>
            网格视图
          </el-radio-button>
          <el-radio-button value="list">
            <el-icon><List /></el-icon>
            列表视图
          </el-radio-button>
        </el-radio-group>
      </div>
      
      <div class="toolbar-right">
        <!-- 搜索框 -->
        <el-input
          v-model="searchKeyword"
          placeholder="搜索文档..."
          style="width: 240px"
          clearable
          @input="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        
        <!-- 筛选器 -->
        <el-select
          v-model="filters.type"
          placeholder="文件类型"
          clearable
          style="width: 120px"
          @change="applyFilters"
        >
          <el-option label="PDF" value="pdf" />
          <el-option label="Word" value="doc" />
          <el-option label="PPT" value="ppt" />
          <el-option label="图片" value="img" />
        </el-select>
        
        <el-select
          v-model="filters.projectId"
          placeholder="项目"
          clearable
          style="width: 140px"
          @change="applyFilters"
        >
          <el-option
            v-for="project in projectStore.projects"
            :key="project.id"
            :label="project.name"
            :value="project.id"
          />
        </el-select>
        
        <!-- 排序 -->
        <el-select
          v-model="sortBy"
          placeholder="排序方式"
          style="width: 140px"
          @change="applySorting"
        >
          <el-option label="更新时间" value="updateTime" />
          <el-option label="创建时间" value="createTime" />
          <el-option label="文件大小" value="size" />
          <el-option label="使用次数" value="usageCount" />
          <el-option label="文件名称" value="title" />
        </el-select>
      </div>
    </div>

    <!-- 文档内容区域 -->
    <div class="documents-content">
      <el-card class="documents-container" shadow="never">
        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <el-icon class="is-loading"><Loading /></el-icon>
          <span class="loading-text">加载中...</span>
        </div>
        
        <!-- 空状态 -->
        <div v-else-if="!filteredDocuments.length" class="empty-state">
          <el-icon class="empty-icon"><DocumentCopy /></el-icon>
          <div class="empty-title">暂无文档</div>
          <div class="empty-description">
            {{ searchKeyword ? '未找到匹配的文档，请尝试其他关键词' : '开始上传您的第一个文档吧' }}
          </div>
          <el-button
            v-if="!searchKeyword"
            type="primary"
            @click="showUploadDialog = true"
          >
            <el-icon><Upload /></el-icon>
            立即上传
          </el-button>
        </div>
        
        <!-- 网格视图 -->
        <div v-else-if="viewMode === 'grid'" class="documents-grid">
          <div
            v-for="doc in paginatedDocuments"
            :key="doc.id"
            class="document-card"
            @click="previewDocument(doc)"
          >
            <div class="card-header">
              <div class="document-icon" :class="doc.type">
                <el-icon>
                  <Document v-if="doc.type === 'pdf'" />
                  <Reading v-else-if="doc.type === 'doc'" />
                  <Present v-else-if="doc.type === 'ppt'" />
                  <Picture v-else />
                </el-icon>
              </div>
              <div class="card-actions">
                <el-dropdown trigger="click" @click.stop>
                  <el-button circle size="small">
                    <el-icon><More /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="previewDocument(doc)">
                        <el-icon><View /></el-icon>
                        预览
                      </el-dropdown-item>
                      <el-dropdown-item @click="downloadDocument(doc)">
                        <el-icon><Download /></el-icon>
                        下载
                      </el-dropdown-item>
                      <el-dropdown-item @click="shareDocument(doc)">
                        <el-icon><Share /></el-icon>
                        分享
                      </el-dropdown-item>
                      <el-dropdown-item divided @click="deleteDocument(doc)">
                        <el-icon><Delete /></el-icon>
                        删除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
            
            <div class="card-body">
              <div class="document-title" :title="doc.title">{{ doc.title }}</div>
              <div class="document-tags">
                <el-tag
                  v-for="tag in doc.tags.slice(0, 2)"
                  :key="tag"
                  size="small"
                  type="info"
                  class="tag-item"
                >
                  {{ tag }}
                </el-tag>
                <span v-if="doc.tags.length > 2" class="more-tags">
                  +{{ doc.tags.length - 2 }}
                </span>
              </div>
              <div class="document-description">{{ doc.description }}</div>
            </div>
            
            <div class="card-footer">
              <div class="footer-left">
                <el-tag size="small" :color="getProjectColor(doc.project)">
                  {{ doc.project }}
                </el-tag>
              </div>
              <div class="footer-right">
                <span class="document-size">{{ doc.size }}</span>
                <span class="document-time">{{ formatTime(doc.updateTime) }}</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 列表视图 -->
        <div v-else class="documents-table">
          <el-table :data="paginatedDocuments" @row-click="previewDocument">
            <el-table-column width="50">
              <template #default="{ row }">
                <div class="table-icon" :class="row.type">
                  <el-icon>
                    <Document v-if="row.type === 'pdf'" />
                    <Reading v-else-if="row.type === 'doc'" />
                    <Present v-else-if="row.type === 'ppt'" />
                    <Picture v-else />
                  </el-icon>
                </div>
              </template>
            </el-table-column>
            
            <el-table-column prop="title" label="文档名称" min-width="200">
              <template #default="{ row }">
                <div class="document-title-cell">
                  <div class="title-text">{{ row.title }}</div>
                  <div class="title-tags">
                    <el-tag
                      v-for="tag in row.tags.slice(0, 2)"
                      :key="tag"
                      size="small"
                      type="info"
                    >
                      {{ tag }}
                    </el-tag>
                  </div>
                </div>
              </template>
            </el-table-column>
            
            <el-table-column prop="project" label="项目" width="120">
              <template #default="{ row }">
                <el-tag size="small" :color="getProjectColor(row.project)">
                  {{ row.project }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="size" label="大小" width="100" />
            
            <el-table-column prop="author" label="上传者" width="100" />
            
            <el-table-column prop="updateTime" label="更新时间" width="120">
              <template #default="{ row }">
                {{ formatTime(row.updateTime) }}
              </template>
            </el-table-column>
            
            <el-table-column prop="usageCount" label="使用次数" width="100">
              <template #default="{ row }">
                <el-tag size="small" type="info">{{ row.usageCount }}</el-tag>
              </template>
            </el-table-column>
            
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row }">
                <div class="table-actions">
                  <el-button size="small" circle @click.stop="previewDocument(row)">
                    <el-icon><View /></el-icon>
                  </el-button>
                  <el-button size="small" circle @click.stop="downloadDocument(row)">
                    <el-icon><Download /></el-icon>
                  </el-button>
                  <el-dropdown trigger="click" @click.stop>
                    <el-button size="small" circle>
                      <el-icon><More /></el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item @click="shareDocument(row)">
                          <el-icon><Share /></el-icon>
                          分享
                        </el-dropdown-item>
                        <el-dropdown-item divided @click="deleteDocument(row)">
                          <el-icon><Delete /></el-icon>
                          删除
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分页 -->
        <div v-if="filteredDocuments.length" class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :total="filteredDocuments.length"
            :page-sizes="[12, 24, 36, 48]"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handlePageChange"
            @size-change="handleSizeChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 文档上传对话框 -->
    <el-dialog
      v-model="showUploadDialog"
      title="上传文档"
      width="500px"
      :before-close="closeUploadDialog"
    >
      <DocumentUpload @success="handleUploadSuccess" @cancel="showUploadDialog = false" />
    </el-dialog>

    <!-- 文档预览对话框 -->
    <el-dialog
      v-model="showPreviewDialog"
      :title="currentPreviewDoc?.title"
      width="80%"
      top="5vh"
      :before-close="closePreviewDialog"
    >
      <DocumentPreview v-if="currentPreviewDoc" :document="currentPreviewDoc" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useDocumentStore } from '@/store/document'
import { useProjectStore } from '@/store/project'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Upload, Grid, List, Search, Document, Reading, Present, Picture,
  More, View, Download, Share, Delete, Loading, DocumentCopy
} from '@element-plus/icons-vue'
import DocumentUpload from '@/components/DocumentUpload.vue'
import DocumentPreview from '@/components/DocumentPreview.vue'

const route = useRoute()
const router = useRouter()
const documentStore = useDocumentStore()
const projectStore = useProjectStore()

// 响应式数据
const viewMode = ref('grid')
const searchKeyword = ref('')
const sortBy = ref('updateTime')
const loading = ref(false)
const showUploadDialog = ref(false)
const showPreviewDialog = ref(false)
const currentPreviewDoc = ref(null)

const filters = reactive({
  type: '',
  projectId: null
})

const pagination = reactive({
  page: 1,
  pageSize: 12
})

// 计算属性
const filteredDocuments = computed(() => {
  let docs = documentStore.documents
  
  // 关键词筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    docs = docs.filter(doc => 
      doc.title.toLowerCase().includes(keyword) ||
      doc.description.toLowerCase().includes(keyword) ||
      doc.tags.some(tag => tag.toLowerCase().includes(keyword)) ||
      doc.author.toLowerCase().includes(keyword)
    )
  }
  
  // 类型筛选
  if (filters.type) {
    docs = docs.filter(doc => doc.type === filters.type)
  }
  
  // 项目筛选
  if (filters.projectId) {
    docs = docs.filter(doc => doc.projectId === filters.projectId)
  }
  
  // 排序
  docs.sort((a, b) => {
    switch (sortBy.value) {
      case 'updateTime':
        return new Date(b.updateTime) - new Date(a.updateTime)
      case 'createTime':
        return new Date(b.createTime) - new Date(a.createTime)
      case 'size':
        return b.sizeBytes - a.sizeBytes
      case 'usageCount':
        return b.usageCount - a.usageCount
      case 'title':
        return a.title.localeCompare(b.title)
      default:
        return 0
    }
  })
  
  return docs
})

const paginatedDocuments = computed(() => {
  const start = (pagination.page - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return filteredDocuments.value.slice(start, end)
})

// 方法
const formatTime = (timeStr) => {
  const now = new Date()
  const time = new Date(timeStr)
  const diff = now - time
  
  const minutes = Math.floor(diff / 60000)
  const hours = Math.floor(minutes / 60)
  const days = Math.floor(hours / 24)
  
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`
  
  return time.toLocaleDateString()
}

const getProjectColor = (projectName) => {
  const project = projectStore.projects.find(p => p.name === projectName)
  return project ? project.color : '#909399'
}

let searchTimer = null
const handleSearch = () => {
  clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    pagination.page = 1 // 重置到第一页
  }, 300)
}

const applyFilters = () => {
  pagination.page = 1 // 重置到第一页
}

const applySorting = () => {
  pagination.page = 1 // 重置到第一页
}

const handlePageChange = (page) => {
  pagination.page = page
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.page = 1
}

const previewDocument = (doc) => {
  currentPreviewDoc.value = doc
  showPreviewDialog.value = true
  documentStore.incrementUsageCount(doc.id)
}

const downloadDocument = (doc) => {
  ElMessage.success(`开始下载：${doc.title}`)
  documentStore.incrementUsageCount(doc.id)
}

const shareDocument = (doc) => {
  const shareUrl = `${window.location.origin}/document/${doc.id}`
  navigator.clipboard.writeText(shareUrl).then(() => {
    ElMessage.success('分享链接已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败，请手动复制链接')
  })
}

const deleteDocument = async (doc) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除文档 "${doc.title}" 吗？此操作不可撤销。`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    documentStore.deleteDocument(doc.id)
    ElMessage.success('文档已删除')
  } catch {
    // 用户取消删除
  }
}

const closeUploadDialog = () => {
  showUploadDialog.value = false
}

const closePreviewDialog = () => {
  showPreviewDialog.value = false
  currentPreviewDoc.value = null
}

const handleUploadSuccess = () => {
  showUploadDialog.value = false
  ElMessage.success('文档上传成功！')
}

// 初始化
onMounted(() => {
  // 处理路由参数
  if (route.query.project) {
    filters.projectId = parseInt(route.query.project)
  }
  if (route.query.type) {
    filters.type = route.query.type
  }
  if (route.query.keyword) {
    searchKeyword.value = route.query.keyword
  }
})

// 监听筛选条件变化，更新URL
watch([() => filters.projectId, () => filters.type, searchKeyword], () => {
  const query = {}
  if (filters.projectId) query.project = filters.projectId
  if (filters.type) query.type = filters.type
  if (searchKeyword.value) query.keyword = searchKeyword.value
  
  router.replace({ query })
}, { deep: true })
</script>

<style lang="scss" scoped>
.documents-page {
  padding: 20px;
  height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
}

.page-header {
  margin-bottom: 24px;
  
  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    
    .page-title {
      font-size: 28px;
      font-weight: 600;
      color: var(--el-text-color-primary);
      margin-bottom: 4px;
    }
    
    .page-subtitle {
      color: var(--el-text-color-secondary);
      font-size: 14px;
    }
  }
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px 20px;
  background: var(--el-bg-color);
  border-radius: var(--radius-large);
  border: 1px solid var(--el-border-color-light);
  
  .toolbar-left, .toolbar-right {
    display: flex;
    align-items: center;
    gap: 12px;
  }
}

.documents-content {
  flex: 1;
  overflow: hidden;
  
  .documents-container {
    height: 100%;
    
    :deep(.el-card__body) {
      height: calc(100% - 20px);
      padding: 20px;
      display: flex;
      flex-direction: column;
    }
  }
}

.documents-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  flex: 1;
  overflow-y: auto;
  padding: 4px;
  
  .document-card {
    border: 1px solid var(--el-border-color-light);
    border-radius: var(--radius-large);
    padding: 16px;
    cursor: pointer;
    transition: all 0.3s ease;
    background: var(--el-bg-color);
    height: 200px;
    display: flex;
    flex-direction: column;
    
    &:hover {
      transform: translateY(-4px);
      box-shadow: var(--shadow-base);
      border-color: var(--el-color-primary);
    }
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 12px;
      
      .document-icon {
        width: 40px;
        height: 40px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20px;
        color: white;
        
        &.pdf { background: var(--gradient-danger); }
        &.doc { background: var(--gradient-primary); }
        &.ppt { background: var(--gradient-warning); }
        &.img { background: var(--gradient-success); }
      }
      
      .card-actions {
        opacity: 0;
        transition: opacity 0.2s ease;
      }
    }
    
    &:hover .card-actions {
      opacity: 1;
    }
    
    .card-body {
      flex: 1;
      
      .document-title {
        font-size: 14px;
        font-weight: 600;
        color: var(--el-text-color-primary);
        margin-bottom: 8px;
        line-height: 1.2;
        @extend .text-ellipsis-2 !optional;
      }
      
      .document-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 4px;
        margin-bottom: 8px;
        
        .tag-item {
          margin: 0;
        }
        
        .more-tags {
          font-size: 12px;
          color: var(--el-text-color-placeholder);
        }
      }
      
      .document-description {
        font-size: 12px;
        color: var(--el-text-color-secondary);
        line-height: 1.4;
        @extend .text-ellipsis-2 !optional;
      }
    }
    
    .card-footer {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 8px;
      padding-top: 8px;
      border-top: 1px solid var(--el-border-color-extra-light);
      
      .footer-right {
        display: flex;
        align-items: center;
        gap: 12px;
        font-size: 12px;
        color: var(--el-text-color-placeholder);
      }
    }
  }
}

.documents-table {
  flex: 1;
  overflow: hidden;
  
  :deep(.el-table) {
    height: 100%;
    
    .table-icon {
      width: 32px;
      height: 32px;
      border-radius: 6px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 16px;
      color: white;
      
      &.pdf { background: var(--el-color-danger); }
      &.doc { background: var(--el-color-primary); }
      &.ppt { background: var(--el-color-warning); }
      &.img { background: var(--el-color-success); }
    }
    
    .document-title-cell {
      .title-text {
        font-weight: 500;
        margin-bottom: 4px;
      }
      
      .title-tags {
        display: flex;
        gap: 4px;
        flex-wrap: wrap;
      }
    }
    
    .table-actions {
      display: flex;
      gap: 4px;
    }
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding-top: 20px;
  border-top: 1px solid var(--el-border-color-lighter);
}

// 响应式设计
@media (max-width: 768px) {
  .documents-page {
    padding: 16px;
  }
  
  .page-header .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .toolbar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
    
    .toolbar-left, .toolbar-right {
      flex-wrap: wrap;
      justify-content: center;
    }
  }
  
  .documents-grid {
    grid-template-columns: 1fr;
  }
}
</style>